package com.offlinerssreader.model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class DBConnections {
	static Connection conn;
	/* user name and pwd only for local testing*/
//	private static final String USER_NAME	= "root";
//	private static final String PASSWORD	= "Kiefsuds";
//	private static final String HOSTNAME	=	"localhost";
//	private static final String PORT		=	"3306";
//	private static final String DBNAME		=	"offlinerssreader";
	private static final String USER_NAME	= "system";
	private static final String PASSWORD	= "manager";
	private static final String HOSTNAME	=	"yado.co.il";
	private static final String PORT		=	"3306";
	private static final String DBNAME		=	"rssreader";
	  // private DataSource dataSource;
	   //private JdbcTemplate jdbcTemplateObject;
	   
	static
	{
		try
	    {
	        System.out.println("Loading the driver...");
	        Class.forName("com.mysql.jdbc.Driver");
	        System.out.println("Loading successed  ---------------");
	        
				//Runs locally - only for maintenance 
				System.out.println("Connected " + HOSTNAME );
				String url = "jdbc:mysql://" + HOSTNAME + ":" + PORT + "/" + DBNAME;
				conn= DriverManager.getConnection(url, USER_NAME, PASSWORD);
				
	        System.out.println((new StringBuilder("conn successed. conn=")).append(conn).toString());
	        createTables();
	    }
	    catch(ClassNotFoundException ex)
	    {
	        System.err.println((new StringBuilder("error loading:")).append(ex.getMessage()).toString());
	    }
	    catch(SQLException ex)
	    {
	        System.err.println((new StringBuilder("error loading:")).append(ex.getMessage()).toString());
	    }

	}
   
    public static Connection getConnection(){
		String url = "jdbc:mysql://" + HOSTNAME + ":" + PORT + "/" + DBNAME;
		try {
			return DriverManager.getConnection(url, USER_NAME, PASSWORD);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
    }
    
    public static void createTables() {
		Statement statement;
		Connection conn = getConnection();
		try {
			statement = conn.createStatement();
			System.out.println("Creating table for Users");
			statement.executeUpdate(User.getCreateTable());
			System.out.println("Creating table for RssFeeds");
			statement.executeUpdate(RssFeed.getCreateTable());
			System.out.println("Creating table for RssItems");
			statement.executeUpdate(RssItem.getCreateTable());
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
    }
}
